package client.gui;

import java.awt.AWTException;
import java.awt.Frame;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import javax.swing.event.MouseInputListener;
import utils.MachineUtils;


public class ClientGui {

    private static ResourceBundle resourceBundle;
    private static TrayIcon trayIcon;
    private static ClientFrame clientFrame;
    private static MenuItem exitItem;
    private static MenuItem webpageItem;
    private static MenuItem stateItem;
    private static MenuItem visibleItem;
    private static PopupMenu popup;
    private static ActionListener exitListener;
    private static ActionListener webpageListener;
    private static ActionListener stateListener;
    private static ActionListener actionListener;
    private static MouseMotionListener mouseMotionListener;
    private static String languageInterface;
    private static boolean showMessage;
    

    public static void main(String args[]) {


        if(args.length == 2){
            languageInterface = new String(args[0]);
            languageInterface = (languageInterface.equals("ptPT")? "ptPT" : "enGB");

            showMessage = new Boolean(args[1]);
        }else{

            languageInterface = new String("enGB");
            showMessage = new Boolean("false");
        }        

        
       
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {         

                if (SystemTray.isSupported()) {
                     try {

                        SystemTray tray = SystemTray.getSystemTray();
                        
                        createResourcebundle(getLocale(languageInterface));
                        
                        createMenuItems();

                        clientFrame = new ClientFrame(resourceBundle);                        
                       
                        createMouseMotion();

                        createAndSetListeners();

                        createPopupMenu();

                        createTrayIcon();

                        tray.add(trayIcon);

                        if(showMessage)
                            createDisplayMessage();

                        clientFrame.setVisible(false);

            } catch (ClassNotFoundException e) {
               JOptionPane.showMessageDialog(null,e.getMessage(),resourceBundle.getString("rArcProblem"),JOptionPane.WARNING_MESSAGE);
            } catch (IOException e) {
               JOptionPane.showMessageDialog(null,e.getMessage(),resourceBundle.getString("rArcProblem"),JOptionPane.WARNING_MESSAGE);
            } catch (AWTException e) {
               JOptionPane.showMessageDialog(null,e.getMessage(),resourceBundle.getString("rArcProblem"),JOptionPane.WARNING_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null,resourceBundle.getString("ComputerNotSupportSystemTray"),resourceBundle.getString("rArcProblem"),JOptionPane.WARNING_MESSAGE);
        }
      }

        });
    }
  

    private static void launchWebPage(){

        String url = "http://arquivo.pt/rarc";

        try {
            if(!MachineUtils.openBrowser(url))
                JOptionPane.showMessageDialog(null,resourceBundle.getString("ComputerNotSupport"),"rArc problems",
                        JOptionPane.ERROR_MESSAGE);

        } catch (URISyntaxException e) {
            JOptionPane.showMessageDialog(null,e.getMessage(),resourceBundle.getString("rArcProblem"),
                        JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
             JOptionPane.showMessageDialog(null,e.getMessage(),resourceBundle.getString("rArcProblem"),
                        JOptionPane.ERROR_MESSAGE);
        }        
    }


    private static void dialogExit(){

            Object[] options = {resourceBundle.getString("Yes"),resourceBundle.getString("No")};

            if(JOptionPane.showOptionDialog(null, resourceBundle.getString("QuestionExit"),"rARC",
               JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[1])==JOptionPane.YES_OPTION){

                if(clientFrame!=null)
                    clientFrame.stopRarcClient();
                System.exit(0);
            }
    }


    private static void startAndStoprArc(){

         if(stateItem.getLabel().equals(resourceBundle.getString("Run"))){

                clientFrame.startRarcClient();
                stateItem.setLabel(resourceBundle.getString("Stop"));

                Image image = Toolkit.getDefaultToolkit().getImage(ClientFrame.class.getResource("/client/gui/images/awp_16x16.gif"));
                trayIcon.setImage(image);

        }else{

            clientFrame.stopRarcClient();
            stateItem.setLabel(resourceBundle.getString("Run"));
            Image image = Toolkit.getDefaultToolkit().getImage(ClientFrame.class.getResource("/client/gui/images/awp_stop_16x16.gif"));
            trayIcon.setImage(image);

        }
    }


    private static void setRarcVisible() {
        if(!clientFrame.isVisible()){
            clientFrame.setVisible(true);
            clientFrame.setState(Frame.NORMAL);
        }else{
            clientFrame.setVisible(false);
        }
    }


    private static Locale getLocale(String arguments){
        
        String language = arguments.substring(0,2);
        String country = arguments.substring(2,4);

        return new Locale(language,country);
    }

    
    private static void createPopupMenu(){
        popup = new PopupMenu();
        popup.add(visibleItem);
        popup.addSeparator();
        popup.add(stateItem);
        popup.addSeparator();
        popup.add(webpageItem);
        popup.addSeparator();
        popup.add(exitItem);
    }

    
    private static void createMenuItems() {
        exitItem = new MenuItem(resourceBundle.getString("Exit"));
        webpageItem = new MenuItem(resourceBundle.getString("Webpage"));
        stateItem = new MenuItem(resourceBundle.getString("Stop"));
        visibleItem = new MenuItem(resourceBundle.getString("ShowHide"));
    }


    private static void createAndSetListeners() {
        exitListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialogExit();
            }
        };
        exitItem.addActionListener(exitListener);

        webpageListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                launchWebPage();
            }
        };
        webpageItem.addActionListener(webpageListener);

        stateListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                startAndStoprArc();
            }
        };
        stateItem.addActionListener(stateListener);

        actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setRarcVisible();
            }
        };
        visibleItem.addActionListener(actionListener);
    }


    private static void createMouseMotion() {
        mouseMotionListener = new MouseInputListener() {
            public void mouseClicked(MouseEvent e) {}
            public void mousePressed(MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            public void mouseExited(MouseEvent e) {}
            public void mouseDragged(MouseEvent e) {}
            public void mouseMoved(MouseEvent e) {
                if(clientFrame.isRarcClientRun()){
                    trayIcon.setToolTip(resourceBundle.getString("TrayIconState"));
                }else{
                    trayIcon.setToolTip(resourceBundle.getString("TrayIconState")+" " +
                            "("+resourceBundle.getString("TrayIconPause")+")");
                }
            }
        };
    }


    private static void createTrayIcon() {

        String resourceLocation = "/client/gui/images/awp_16x16.gif";

        Image image = Toolkit.getDefaultToolkit().getImage(ClientFrame.class.getResource(resourceLocation));
        
        trayIcon = new TrayIcon(image,resourceBundle.getString("TrayIcon"), popup);
        trayIcon.setImageAutoSize(true);
        trayIcon.addActionListener(actionListener);
        trayIcon.addMouseMotionListener(mouseMotionListener);
    }


    private static void createResourcebundle(Locale locale) {
        String resourceLocation = "client.gui.language/Language";

        resourceBundle = ResourceBundle.getBundle(resourceLocation,locale);
    }

    
    private static void createDisplayMessage(){
        trayIcon.displayMessage(resourceBundle.getString("TrayIcon"),
                resourceBundle.getString("TrayIconRun"), TrayIcon.MessageType.INFO);
    }

    
}
